﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using Xceed.Wpf.Toolkit.PropertyGrid;
using Xceed.Wpf.Toolkit.PropertyGrid.Editors;

namespace ABCat.Plugins.FilteringLogics.Standard
{
	public class FilteredComboBoxEditor : ITypeEditor
	{
		#region + Fields +

		private static readonly Dictionary<string, ObservableCollection<string>> Sources = new Dictionary<string, ObservableCollection<string>>();

		#endregion
		#region + Logic +

		public static void Register(string propertyItemName, ObservableCollection<string> itemsSource)
		{
			Sources.Add(propertyItemName, itemsSource);
		}

		public FrameworkElement ResolveEditor(PropertyItem propertyItem)
		{
			ObservableCollection<string> itemsSource;
			if (Sources.TryGetValue(propertyItem.PropertyDescriptor.Name, out itemsSource))
			{
				var fcmb = new AutoFilterCmb();
				var binding = new Binding("Value");
				binding.Source = propertyItem;
				binding.ValidatesOnExceptions = true;
				binding.ValidatesOnDataErrors = true;
				binding.Mode = propertyItem.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay;
				BindingOperations.SetBinding(fcmb, ComboBox.TextProperty, binding);
				fcmb.ItemsSource = itemsSource;
				return fcmb;
			}
			else
			{
				var textBox = new TextBox();
				var binding = new Binding("Value");
				binding.Source = propertyItem;
				binding.ValidatesOnExceptions = true;
				binding.ValidatesOnDataErrors = true;
				binding.Mode = propertyItem.IsReadOnly ? BindingMode.OneWay : BindingMode.TwoWay;
				BindingOperations.SetBinding(textBox, TextBox.TextProperty, binding);
				return textBox;
			}
		}

		#endregion
	}
}